<?php

namespace Modules\Good\Http\Controllers;
use Modules\Good\Requests\GoodsRequest;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\Category\Models\Category;
use Modules\Good\Models\Good;
use Modules\Good\Http\Resources\GoodResource;
use Illuminate\Support\Facades\Log;
class GoodController extends Controller
{
public function index(Request $request)
{
$goods = Good::query()
    ->when($request->query('title'), fn($q,$title) => $q->where('title','like',"%{$title}%"))
    ->when($request->query('is_on') !== null, fn($q) => $q->where('is_on', $request->query('is_on') ? 1 : 0))
    ->when($request->query('include'), function ($query, $include) {
        $relations = explode(',', $include);
        $allowed = ['category','user','comments'];
        $relations = array_filter($relations, fn($r) => in_array($r,$allowed));
        if($relations) $query->with($relations);
    })
    ->paginate(9);


    $goodsResource = GoodResource::collection($goods);

    return response()->json([
        'status' => true,
        'message' => '商品列表获取成功',
        'data' => $goodsResource,
        'pagination' => [
            'total' => $goods->total(),
            'per_page' => $goods->perPage(),
            'current_page' => $goods->currentPage(),
            'last_page' => $goods->lastPage(),
            'from' => $goods->firstItem(),
            'to' => $goods->lastItem(),
        ],
    ]);
}

    public function show($id){
        // $good = Good::find($id);
        //with预加载
        $good=Good::with(['user', 'category'])->find($id);
        if (!$good) {
            return response()->json([
                'message' => '商品不存在'
            ], 404);
        }
        //API Resource的写法
        return new GoodResource($good);
    }

    public function store(GoodsRequest $request){
        // 创建商品
        $catagotry=Category::find($request->category_id);
        
        if(!$catagotry) return response()->json(['status' => false,'message' => '分类不存在',], 404);
        if($catagotry->status!=1) return response()->json(['status' => false,'message' => '分类已禁用',], 400);
        if($catagotry->level!=3) return response()->json(['status' => false,'message' => '只能向三级分类添加',], 400);
        $good = Good::create($request->validated());
        return response()->json([
            'status' => true,
            'message' => '商品创建成功',
            'data' => $good
        ], 201);
    }


public function update(GoodsRequest $request, $id)
{
    try {
        Log::info("商品更新请求：", [
            'id' => $id,
            'request_data' => $request->all()
        ]);

        $category = Category::find($request->category_id);
        if (!$category) {
            Log::warning("分类不存在", ['category_id' => $request->category_id]);
            return response()->json(['status' => false, 'message' => '分类不存在'], 404);
        }
        if ($category->status != 1) {
            Log::warning("分类已禁用", ['category_id' => $request->category_id]);
            return response()->json(['status' => false, 'message' => '分类已禁用'], 400);
        }
        if ($category->level != 3) {
            Log::warning("分类层级错误", ['category_id' => $request->category_id, 'level' => $category->level]);
            return response()->json(['status' => false, 'message' => '只能向三级分类添加'], 400);
        }

        $good = Good::find($id);
        if (!$good) {
            Log::warning("商品不存在", ['id' => $id]);
            return response()->json(['status' => false, 'message' => '商品不存在'], 404);
        }

        // 更新数据
        $good->update($request->validated());
        $good->refresh();

        Log::info("商品更新成功", [
            'id' => $id,
            'updated_data' => $good->toArray()
        ]);
        
        return response()->json([
            'status' => true,
            'message' => '商品更新成功',
            'data' => $good
        ], 200);

    } catch (\Exception $e) {
        Log::error("商品更新异常", [
            'id' => $id,
            'error' => $e->getMessage(),
            'trace' => $e->getTraceAsString()
        ]);

        return response()->json([
            'status' => false,
            'message' => '服务器异常，请稍后再试',
            'error' => $e->getMessage() // 生产环境可以去掉，避免暴露敏感信息
        ], 500);
    }
}

public function isOn($id){
    $good = Good::findOrFail($id); // 找不到直接抛 404
    $good->is_on = !$good->is_on;
    $good->save();

    return response()->json([
        'status' => true,
        'message' => '商品状态更新成功',
        'data' => $good
    ], 200);
}


}
